#include "ezqthread.h"
#include "log/EZQLOG.h"

EZQThread::EZQThread(QObject *obj,EZQThreadFunc0 fun) :
    QThread(0)
{
    _threadFunc = fun;
    _obj = obj;
}

EZQThread::~EZQThread()
{
//    EZDebug << "~EZQThread";
}

void EZQThread::run()
{
    if(_obj && _threadFunc){
        (_obj->*_threadFunc)(this);
    }
}
void EZQThread::onFinish()
{
    Release();
}

EZQThreadFunc0 EZQThread::threadFunc() const
{
    return _threadFunc;
}

void EZQThread::setThreadFunc(EZQThreadFunc0 threadFunc)
{
    _threadFunc = threadFunc;
}
QObject *EZQThread::obj() const
{
    return _obj;
}

void EZQThread::setObj(QObject *obj)
{
    _obj = obj;
}


void EZQThread::start(Priority p)
{
    Retain();
    disconnect(this,SIGNAL(finished()),this,SLOT(onFinish())); //prevent call starts
    connect(this,SIGNAL(finished()),this,SLOT(onFinish()));
    QThread::start(p);
}

void EZQThread::Release()
{
    retainCount--;
    if (retainCount==0) {
        deleteLater();
    }
}

QVariant EZQThread::getUserData(const QString &key)
{
    if(_userDataMap.constFind(key)==_userDataMap.end()){
        return QVariant(QVariant::Invalid);
    }
    return _userDataMap[key];
}

void EZQThread::setUserData(const QString &key,const QVariant &value)
{
    _userDataMap.insert(key,value);
}

